import { ref } from "vue";
import api from "@/api";

/**
 * 分页管理 Hook
 *
 * 使用须知：
 * - 获取表格数据方法名统一为 getData
 * - 数据集合命名为 data
 * - 提交表单命名为 searchForm，参数 page 默认值1
 * - getData获取数据成功必须return { total } total数据总条数
 * - 接口参数 urls 从外到内填写接口名称
 *
 * 接口结构示例：外层文件夹名称 > 不同js文件分类 > 接口方法名称
 * urls: {
 *   0: 'schoolConfig',
 *   1: 'classCircleList',
 *   2: 'handleDelete'
 * }
 *
 * 实际调取过程：api['schoolConfig']['classCircleList']['getPageData']()
 */
export function usePage(options) {
    const {
        urls,
        searchForm: initialSearchForm = {},
        pageSize: initialPageSize = 15,
        dataCallBack,
        searchCallBack
    } = options;
    // 响应式状态
    const reqNum = ref(0);

    // 表格分页参数
    const page = ref({
        currentPage: 1,
        total: 0,
        layout: "total, sizes, prev, pager, next, jumper",
        pageSize: initialPageSize,
        pageSizes: [5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300]
    });

    const loading = ref(true);

    // 搜索表单
    const searchForm = ref({
        page: 1,
        limit: initialPageSize,
        ...initialSearchForm
    });
    // 数据列表
    const data = ref([]);

    // 终端ID字符串
    const terminalIds = ref("");

    /**
     * 搜索事件处理
     */
    const handleSearchChange = async (params, done) => {
        console.log("params", params, searchForm.value);

        // 循环多选下拉框
        terminalIds.value = "";
        if (searchForm.value.terminalIds && searchForm.value.terminalIds.length) {
            for (let i = 0; i < params.terminalIds.length; i++) {
                terminalIds.value += params.terminalIds[i] + ",";
            }
            terminalIds.value = terminalIds.value.substring(0, terminalIds.value.length - 1);
        }
        searchForm.value.terminalId = terminalIds.value;

        loading.value = true;
        searchForm.value.page = 1;
        page.value.currentPage = 1;

        // 将schoolName转为schoolId
        if (searchForm.value.schoolName && !isNaN(Number(searchForm.value.schoolName))) {
            searchForm.value.schoolId = searchForm.value.schoolName;
        }

        // 自定义搜索回调 - 处理日期范围
        if (searchForm.value.date && searchForm.value.date.length) {
            searchForm.value.startTime = searchForm.value.date[0];
            searchForm.value.endTime = searchForm.value.date[1];
        }

        if (searchForm.value.date && searchForm.value.date.length) {
            searchForm.value.createTimeBefore = searchForm.value.date[0];
            searchForm.value.createTimeAfter = searchForm.value.date[1];
        }

        console.log("params", params, searchForm.value);

        // 执行搜索回调或获取数据
        if (searchCallBack) {
            await searchCallBack(Object.assign({}, searchForm.value));
        } else {
            await getData(searchForm.value);
        }

        loading.value = false;

        if (done) done();

        // 去掉请求'所有页数'的属性，在输入具体名字的时候不查询
        if (searchForm.value.isSearchCount === false) {
            Reflect.deleteProperty(searchForm.value, "isSearchCount");
        }
    };

    /**
     * 清空搜索回调
     */
    const handleSearchReset = () => {
        searchForm.value.page = 1;
        searchForm.value.limit = initialPageSize;
    };

    /**
     * 分页加载
     */
    const onLoad = async _pageData => {
        // isNot 第一次加载不请求
        searchForm.value.page = page.value.currentPage;
        searchForm.value.limit = page.value.pageSize;
        await getData(searchForm.value);
    };

    /**
     * 获取数据 - 调取API
     * @param param 查询参数
     */
    const getData = async param => {
        // 处理提交数据
        const subForm = Object.assign({}, param);
        // delete subForm.schoolName;
        // delete subForm.date;
        // delete subForm.$schoolName;
        loading.value = true;
        try {
            // 调取API - 根据urls配置动态获取API方法
            let apiMethod: any = api;
            Object.keys(urls).forEach(key => {
                apiMethod = apiMethod[urls[Number(key)]];
            });
            // 调用API
            const res = await apiMethod(subForm);

            // 如果请求正常但是data返回null的情况特殊处理
            if (res.code === 200 && res.data === null) {
                res.data = [];
            }

            if (dataCallBack) {
                await dataCallBack(res.data);
            } else {
                data.value = (res.data && res.data.records) || res.data || [];
            }

            page.value.total = (res.data && res.data.total) || (res.data && res.data.totalCount) || 1;
            loading.value = false;
        } catch (error) {
            console.error("获取数据失败:", error);
            loading.value = false;
        }
    };

    return {
        page,
        loading,
        searchForm,
        data,
        terminalIds,
        handleSearchChange,
        handleSearchReset,
        onLoad,
        getData
    };
}
